package com.dg.dgrmi.handler;

import java.util.*;

import org.xsocket.connection.INonBlockingConnection;

/**
 * A common static way to access the Socket
 * which started the Delegator Thread. A very useful
 * way to know who called the current Method.
 *
 * @author lipe
 * @date   07/10/2006
 *
 * @see	   net.sf.lipermi.handler.CallHandler
 */
public class CallLookup {

    private static Map<Thread,
                       ConnectionHandler> connectionMap = Collections.
            synchronizedMap(new
                            HashMap<Thread, ConnectionHandler>());

    /**
     * Get the current Socket for this call.
     * Only works in the main thread call.
     *
     * @return Socket which started the Delegator Thread
     */
    public static INonBlockingConnection getCurrentSocket() {
        ConnectionHandler handler = connectionMap.get(Thread.currentThread());
        return (handler == null ? null : handler.getSocket());
    }

    static void handlingMe(ConnectionHandler connectionHandler) {
        synchronized (connectionMap) {
            connectionMap.put(Thread.currentThread(), connectionHandler);
        }
    }

    static void forgetMe() {
        synchronized (connectionMap) {
            connectionMap.remove(Thread.currentThread());
        }
    }
}
